package com.jcbase.core.weixin.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcbase.core.BaseConstance;
import com.jcbase.core.util.WeiXinUtils;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;

/**
 * @category 授权
 * 
 * @author yiz
 * @date 2016年8月8日 下午4:17:41
 * @version 1.0.0 
 * @copyright 
 */
public class Oauth2Interceptor implements Interceptor {
	private static final Logger logger = LoggerFactory.getLogger(Oauth2Interceptor.class);

	@Override
	public void intercept(Invocation inv) {
		logger.info("OAuth拦截器开始");
		Controller controller = inv.getController();
		String toUserName = controller.getPara("toUserName");
		//是否开发模式
		boolean devMode = PropKit.getBoolean("devMode", false);
		try {
			ApiConfigKit.setThreadLocalApiConfig(WeiXinUtils.getApiConfig(toUserName));
			String openid = controller.getCookie(BaseConstance.OPENID_COOKIE_KEY);
			logger.info("openid={}", openid);
			if (StringUtils.isBlank(openid) && !devMode) {
				//重定向至授权页面并返回
				controller.redirect("/wx/toOauth?redirect_url=" + BaseConstance.DOMAIN);
			} else {
				inv.invoke();
			}
		} finally {
			ApiConfigKit.removeThreadLocalApiConfig();
		}
	}

}
